/**
* Copyright © 2018 深圳市巨鼎医疗设备有限公司
*/
package com.zl.websocket.service.impl;

import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import com.zl.websocket.constants.WebsocketConstants;
import com.zl.websocket.entity.WebsocketMessage;
import com.zl.websocket.entity.WebsocketMessageTransform;
import com.zl.websocket.service.WebsocketSender;

/**
 * websocket消息推送者，<strong>不要直接调用这个bean直接推送消息</strong>
 * 
 * @author Zhouych
 * @Date: 2018年6月29日 上午9:40:00
 * @since JDK 1.8
 */
@Service
public class WebsocketSenderImpl implements WebsocketSender {

	@Autowired
	private SimpMessagingTemplate simpMessagingTemplate;

	public void send(WebsocketMessageTransform wmt) {
		if (null != wmt) {
			Set<String> userIds = wmt.getUserIds();
			WebsocketMessage websocketMessage = wmt.getPayload();
			// 连接通道测试消息无需理会直接返回
			if (WebsocketConstants.MESSAGE_TYPE_TEST == websocketMessage.getMessageType()) {
				return;
			}
			if (null == userIds || userIds.isEmpty()) {
				convertAndSend(websocketMessage);
			} else {
				convertAndSendToUsers(userIds, websocketMessage);
			}
		}
	}

	private void convertAndSend(WebsocketMessage message) {
		simpMessagingTemplate.convertAndSend(WebsocketConstants.TOPIC_DESTINATION, message);
	}

	private void convertAndSendToUsers(Set<String> userIds, WebsocketMessage message) {
		for (String userId : userIds) {
			if (StringUtils.isNotBlank(userId)) {
				simpMessagingTemplate.convertAndSendToUser(userId, WebsocketConstants.USER_DESTINATION, message);
			}
		}
	}
}
